package com.edushare.activity;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

import com.edushare.R;
import com.edushare.controller.EntityController;
import com.edushare.controller.GroupController;
import com.edushare.controller.GroupMediaController;
import com.edushare.controller.HttpUploader;
import com.edushare.controller.UserFunctions;
import com.edushare.entity.Member;
import com.edushare.entity.User;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class GroupDetail extends Activity {

	public static final String LOG_TAG = "UnifiqDraw";
	public static final String PICTURE_FILE_ID = "picture";
	public static final String TMP_FILE_NAME = ".unifiq";
	private static final int CAMERA_REQUEST_CODE = 666;
	private static final int GALLERY_REQUEST_CODE = 777;
	private File mPictureFile;

	Intent i;
	TextView txtgname, txtgdesc;
	ImageView groupIconIV;
	ProgressBar progBar;
	EntityController controller = new EntityController();
	String groupName;
	MenuItem groupMenuItem;
	int groupID, userID;
	boolean isUserMember = false;
	GroupController gc = new GroupController();
	String imagename = "";
	private ListView listview;
	private ArrayList<Member> _memberList = new ArrayList<Member>();
	ArrayList<Member> memberList = new ArrayList<Member>();
	ArrayList<Member> member_list = new ArrayList<Member>();
	private class MyNetworkTask extends AsyncTask<URL, Void, Bitmap> {

		ImageView tIV;
		ProgressBar pb;

		public MyNetworkTask(ImageView iv, ProgressBar progBar) {
			tIV = iv;
			pb = progBar;
		}// constructor

		@Override
		protected Bitmap doInBackground(URL... urls) {

			Bitmap networkBitmap = null;

			URL networkUrl = urls[0]; // Load the first element
			try {
				networkBitmap = BitmapFactory.decodeStream(networkUrl
						.openConnection().getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}

			return networkBitmap;
		}// return bitmap

		@Override
		protected void onPostExecute(Bitmap result) {
			tIV.setImageBitmap(result);
			tIV.setVisibility(View.VISIBLE);
			pb.setVisibility(View.GONE);
		}// hide progress bar

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_detail);

		// Initialize controls
		txtgname = (TextView) findViewById(R.id.groupNameTV);
		txtgdesc = (TextView) findViewById(R.id.groupDescTV);
		groupIconIV = (ImageView) findViewById(R.id.groupIconIV);
		progBar = (ProgressBar) findViewById(R.id.progBar);
		registerForContextMenu(groupIconIV);
		listview = (ListView) findViewById(R.id.memberList);

		// get intent values
		i = getIntent();
		groupID = i.getExtras().getInt("groupid");
		groupName = i.getExtras().getString("groupname");

		// set group text
		txtgname.setText(i.getExtras().getString("groupname"));
		txtgdesc.setText(i.getExtras().getString("groupdescription"));

		// Load bitmap from internet
		URL onLineURL;
		try {
			onLineURL = new URL(i.getExtras().getString("groupimagepath"));
			new MyNetworkTask(groupIconIV, progBar).execute(onLineURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onResume() {
		super.onResume();

		_memberList.clear();

		new getMembers().execute();
		
		for (int i = 0; i < member_list.size(); i++) {

			int userID = member_list.get(i).getUserID();

			System.out.println("userid>>>>>" + userID);
			String name = member_list.get(i).getName();
			String email = member_list.get(i).getEmail();
			String profilePic = member_list.get(i).getProfilePic();

			Member _MemberModel = new Member();
			_MemberModel.setEmail(email);
			_MemberModel.setName(name);
			_MemberModel.setProfilePic(profilePic);
			_MemberModel.setUserID(userID);
			_MemberModel.setGroupID(groupID);

			_memberList.add(_MemberModel);
		}

		listview.setAdapter(new ListAdapter(this));

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int temp, long arg3) {

				int _groupID = _memberList.get(temp).getGroupID();
				String _mName = _memberList.get(temp).getName().trim();
				int _userID = _memberList.get(temp).getUserID();
				String _mEmail = _memberList.get(temp).getEmail().trim();
				String _mProfilePic = _memberList.get(temp).getProfilePic().trim();
				
				Intent intent = new Intent(getApplicationContext(),
						MemberDetail.class);

				Bundle bundle = new Bundle();
				
				bundle.putInt("groupid", _groupID);
				bundle.putInt("userID", _userID);
				bundle.putString("name", _mName);
				bundle.putString("email", _mEmail);
				bundle.putString("profilePic", _mProfilePic);
				
				intent.putExtras(bundle);
				startActivity(intent);

				/*
				 * Get back byte[] byteArray =
				 * getIntent().getByteArrayExtra("image"); Bitmap bmp =
				 * BitmapFactory.decodeByteArray(byteArray, 0,
				 * byteArray.length);
				 */
			}

		});
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Icon Options");
		menu.add(0, v.getId(), 0, "Draw on a picture");
		menu.add(0, v.getId(), 0, "Change group icon");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Draw on a picture") {
			loadPicture();
		} else if (item.getTitle() == "Change group icon") {
			replacePicture();
		}
		return true;
	}

	private String getRealPathFromURI(Uri contentUri) {

		String[] proj = { MediaColumns.DATA };
		android.database.Cursor cursor = getContentResolver().query(contentUri,
				proj, // Which
				// columns
				// to
				// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	/**
	 * Starts an activity for loading a picture.
	 */
	private void loadPicture() {
		Intent intent = new Intent(Intent.ACTION_PICK,
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, GALLERY_REQUEST_CODE);
	}

	/**
	 * Starts an activity for replacing picture
	 */
	private void replacePicture() {
		// To open up a gallery browser
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				1);

	}

	/**
	 * Starts draw activity with given background.
	 */
	private void draw() {
		if (mPictureFile != null) {
			Intent intent = new Intent(this, DrawActivity.class);
			intent.putExtra(PICTURE_FILE_ID, mPictureFile);
			startActivity(intent);
		}
	}

	/**
	 * Gets path of an image from the gallery.
	 * 
	 * @param uri
	 *            Image Uri
	 * @return Image absolute path
	 */
	private String getImagePath(final Uri uri) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(uri, projection, null, null,
				null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CAMERA_REQUEST_CODE:
				draw();
				break;
			case GALLERY_REQUEST_CODE:
				mPictureFile = new File(getImagePath(data.getData()));
				draw();
				break;
			case 1:
				Uri currImageURI = data.getData();
				System.out.println("Current image Path is "
						+ getRealPathFromURI(currImageURI));

				HttpUploader uploader = new HttpUploader();
				try {
					imagename = uploader.execute(
							getRealPathFromURI(currImageURI)).get();
					new UpdateIcon().execute();

				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}

				break;
			default:
				break;
			}
		}
	}

	class UpdateIcon extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			gc.updateGroupIcon(groupID, imagename);
			return null;
		}

		protected void onPostExecute(String file_url) {

			// Load bitmap from internet
			URL onLineURL;
			try {
				onLineURL = new URL(
						"http://unifiq.5kportal.com/images/post_images/"
								+ imagename);

				new MyNetworkTask(groupIconIV, progBar).execute(onLineURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
	}

	class getMembers extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			memberList = gc.getMembers(groupID);
			return null;
		}

		protected void onPostExecute(String file_url) {

			for (int i = 0; i < memberList.size(); i++) {

				int groupID = memberList.get(i).getGroupID();
				int userID = memberList.get(i).getUserID();
				String name = memberList.get(i).getName();
				String email = memberList.get(i).getEmail();
				String mpic = memberList.get(i).getProfilePic();

				Member _MemberModel = new Member();
				_MemberModel.setUserID(userID);
				_MemberModel.setGroupID(groupID);
				_MemberModel.setName(name);
				_MemberModel.setEmail(email);
				_MemberModel.setProfilePic(mpic);

				_memberList.add(_MemberModel);
			}

			listview = (ListView) findViewById(R.id.memberList);
			ListAdapter myAdapter = new ListAdapter(getApplicationContext());
			listview.setAdapter(myAdapter);
			myAdapter.notifyDataSetChanged();

			listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int temp, long arg3) {

					int _groupID = _memberList.get(temp).getGroupID();
					String _mName = _memberList.get(temp).getName().trim();
					int _userID = _memberList.get(temp).getUserID();
					String _mEmail = _memberList.get(temp).getEmail().trim();
					String _mProfilePic = _memberList.get(temp).getProfilePic().trim();
					
					Intent intent = new Intent(getApplicationContext(),
							MemberDetail.class);

					Bundle bundle = new Bundle();
					bundle.putInt("groupid", _groupID);
					bundle.putInt("userID", _userID);
					bundle.putString("name", _mName);
					bundle.putString("email", _mEmail);
					bundle.putString("profilePic", _mProfilePic);

					intent.putExtras(bundle);
					startActivity(intent);

					/*
					 * Get back byte[] byteArray =
					 * getIntent().getByteArrayExtra("image"); Bitmap bmp =
					 * BitmapFactory.decodeByteArray(byteArray, 0,
					 * byteArray.length);
					 */
				}

			});

		}
	}

	private class ListAdapter extends BaseAdapter {

		LayoutInflater inflater;
		ViewHolder viewHolder;

		public ListAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return _memberList.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			convertView = inflater.inflate(R.layout.member_list_row, null);
			viewHolder = new ViewHolder();

			viewHolder.memberIconIV = (ImageView) convertView
					.findViewById(R.id.memberIconIV);
			viewHolder.memberNameTV = (TextView) convertView
					.findViewById(R.id.memberNameTV);
			viewHolder.progBar = (ProgressBar) convertView
					.findViewById(R.id.progBar);

			convertView.setTag(viewHolder);

			viewHolder.memberNameTV
					.setText(_memberList.get(position).getName().trim());

			// Load bitmap from internet
			URL onLineURL;
			try {
				onLineURL = new URL(_memberList.get(position).getProfilePic());
				new MyNetworkTask(viewHolder.memberIconIV, viewHolder.progBar)
						.execute(onLineURL);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
	
/*
			final int temp = position;
			
			   (convertView.findViewById(R.id.groupRow)) .setOnClickListener(new
			   OnClickListener() {
			   
			   @Override public void onClick(View arg0) {
			   
			   String _groupName = _groupList.get(temp) .getName().trim();
			   String _groupdescription = _groupList.get(temp)
			   .getDescription().trim(); String _groupimagepath =
			   _groupList.get(temp) .getImagePath().trim();
			   
			   Intent intent = new Intent(getActivity(), GroupDetail.class);
			   
			   Bundle bundle = new Bundle(); bundle.putString("groupName",
			   _groupName); bundle.putString("groupdescription",
			   _groupdescription); bundle.putString("groupimagepath",
			   _groupimagepath); intent.putExtras(bundle);
			   startActivity(intent);
			   
			   } });
			 */
			return convertView;

		}
	}

	private class ViewHolder {
		public TextView memberNameTV;
		public ImageView memberIconIV;
		public ProgressBar progBar;
	}
	



}
